<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Story extends La_Controller {
	function __construct() {
		parent::__construct();
		$this->load->model(array('Category_model', 'City_model','User_model','Emergency_model'));
//		$this->load->model('City_model');
//		$this->load->model('User_model');
//		$this->load->model('Emergency_model');
		$this->data['nav'] = 'story';
		$this->data['first_level_categories'] = $this->Category_model->find_son_category(1);
	}
	/**
	 * 事项一级列表页面
	 */
	function index() {
		$this->page_title("事项-行动网");
		$current_category_id = $this->uri->segment(2);
		if (empty($current_category_id)) {
			$current_category_id = 2;
		}
		$this->_lists($current_category_id);
	}
	/**
	 * 发布事项
	 */
	function create() {
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('story/create')), "请你先登录");
		}
		$this->page_title("发布事项-行动网");
		if ($_SERVER['REQUEST_METHOD']  == 'POST') {
			$title = $this->input->post('title');
			$bonus = $this->input->post('bonus');
			$is_public = $this->input->post('is_public');
			$time_cost = $this->input->post('time_cost');
			$introduction = $this->input->post('introduction');
			$contact = $this->input->post('contact');
			$category_id = $this->input->post('category_id');
			$province_id = intval($this->input->post('province'));
			$city_id = intval( $this->input->post('city'));
			$area_id = intval($this->input->post('area'));
			$id = intval($this->input->post('id'));
			$user_id = intval($this->input->post('user_id'));
			if (!empty($user_id)) {
				$status = 0;
			} else {
				$status = 1;
			}
			$upload_files = $this->input->post('upload_files');
			
			$config['upload_path'] = './img/uploads/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size']	= '4096';
			$this->load->library('upload', $config);
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			$this->form_validation->set_rules('category_id', '事项类别', 'required');
			$this->form_validation->set_rules('title', '事项标题', 'required');
			$this->form_validation->set_rules('bonus', '酬金', 'required');
			if ($this->form_validation->run() == FALSE)
			{
				$this->data['title'] = $title;
				$this->data['bonus'] = $bonus;
				$this->data['introduction'] = $introduction;
				$this->data['contact'] = $contact;
				$this->data['time_cost'] = $time_cost;
				$this->data['is_public'] = $is_public;
				$this->data['user_id'] = empty($user_id) ? "" : $user_id;
				$this->data['province_id'] = $province_id;
				$this->data['city_id'] = $city_id;
				$this->data['area_id'] = $area_id;
				$this->data['id'] = $id;
				
				$this->data['provinces'] = $this->City_model->find_all_province();
				$this->data['first_level_categories'] = $this->Category_model->find_son_category(1);
				$this->load->view('story/edit', $this->data);

			} else {
				$current_user = $this->authorize->current_user();
				$data = array( 'title' => $title, 'bonus' => $bonus,'created_by' => $current_user, 
								'time_cost' => $time_cost,'introduction'=> $introduction, 'contact' => $contact,
								'is_public' => $is_public, 'category_id' => $category_id, 'province_id' => $province_id,
								'city_id' => $city_id, 'area_id' => $area_id, 'status' => $status);
				if (!empty($id)) {
					$data['id'] = $id;
				} else {
					$data['created'] = date("Y-m-d H:i:s");
				}
				$story_id = $this->Emergency_model->add($data);
				if(!empty($upload_files)) {
					foreach($upload_files as $upload_file) {
						$upload_array = split('`', $upload_file);
						//if(count($upload_array !=4 )) continue;
						$pic_data = array('file_name'=>$upload_array[0], 
											'raw_name' => $upload_array[1],
											'file_ext' => $upload_array[2],
											'file_type' => ''
											);
						$this->Emergency_model->add_pic($story_id, $pic_data);
					}
				}
				if (!empty($user_id)) {
					$this->load->model("Invite_model");
					$invite_data = array('user_id' => $user_id, 'target_id' => $story_id, "target_type" => 'story', 'created' => date("Y-m-d H:i:s"));
					$this->Invite_model->add($invite_data);
					$post_data['msg_to_id'] = $user_id;
					$post_data['is_system'] = 1;
					$post_data['subject'] = "你被邀请完成此事项--" . $title;
					$post_data['content'] = "尊敬的用户： <br/>
			          " . $current_user . "<br/> 在行动网邀请完成此事项<a href='/story/show/" . $story_id. "'>" . $title . "</a>";
					$post_data['msg_from_id'] = 0;
					$post_data['msg_from'] = '行动网';
					$post_data['created'] = date("Y-m-d H:i:s");
					$post_data['related_id'] = 0;
					$this->load->model('Message_model');
					$this->Message_model->add($post_data);
				}
				$this->load->model("User_card_model");
				$card_count = $this->User_card_model->get_cards_count($current_user);
				$this->load->view('story/edit_success', array('story_id'=>$story_id, 'card_count' => $card_count));
			}
		} else {
			$this->data['provinces'] = $this->City_model->find_all_province();
			$this->data['first_level_categories'] = $this->Category_model->find_son_category(1);
			$user_id = $this->input->get("user_id");
			if (!empty($user_id)) {
				$this->data['user_id'] = $user_id;
			}
			$this->load->view('story/edit', $this->data);
		}
	}
	/**
	 * 事项二级列表
	 */
	public function lists() {
		$this->page_title("事项-行动网");
		$sub_category_id = intval($this->uri->segment(3));
		$current_category_id = $this->Category_model->find_father_category($sub_category_id);
		$this->_lists($current_category_id, $sub_category_id);
	}
	/**
	 * 列表
	 * @param int $current_category_id 一级分类id
	 * @param int $sub_category_id 二级分类id
	 */
	private function _lists($current_category_id, $sub_category_id = null) {
		$offset = intval($this->uri->segment(4));
		$this->data['current_category_id'] = $current_category_id;
		$this->data['provinces'] = $this->City_model->find_all_province();
		$this->data['tips_categories'] = $this->Category_model->find_son_category($current_category_id);
		$this->data['sub_category_id'] = ($sub_category_id ? $sub_category_id : (empty($this->data['tips_categories'][0]['id']) ? -1 : $this->data['tips_categories'][0]['id']));
		
		
		$this->data['story_count'] = $this->Emergency_model->get_count_by_category_id($this->data['sub_category_id']);
		$this->load->library('pager');
		$config['base_url'] = site_url("story/lists" . "/" . $this->data['sub_category_id'] ) . "/";
		$config['total_rows'] = $this->data['story_count'];
		$config['per_page'] = LA_PAGE_SIZE;
		$config['uri_segment'] = 4;
		$this->pager->initialize($config);
		$this->data['stories'] = $this->Emergency_model->find_by_category_id($this->data['sub_category_id'], $offset, $config['per_page']);
		$this->data['pager'] =  $this->pager->create_links();
		
		$this->load->view('story/index', $this->data);
	}
	
	/**
	 * 搜索列表
	 */
	public function search() {
		$this->data['provinces'] = $this->City_model->find_all_province();
		$this->load->view('story/search', $this->data);
	}
	
	/**
	 * 发布事项
	 */
	public function edit() {
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('story/create')), "请你先登录");
		}
		$story_id = intval($this->uri->segment(3));
		$story = $this->Emergency_model->find_by_id($story_id);
		
		$current_user = $this->authorize->current_user();
		if ($current_user != $story['created_by']) {
			la_redirect('/story/show/' . $story_id , "无权限操作");
		}
		$this->data['provinces'] = $this->City_model->find_all_province();
		$this->data['first_level_categories'] = $this->Category_model->find_son_category(1);
		$this->data['first_level_category_id'] = $this->Category_model->find_father_category($story['category_id']);
		$this->data = array_merge($this->data, $story);
		$this->load->view('story/edit', $this->data);
	}
	
	/**
	 * 事项发布成功
	 */
	public function edit_success() {
		$this->page_title("事项发布成功-行动网");
		$this->load->view('story/edit_success', $this->data);
	}
	/**
	 * 单条事项的查看
	 */
	public function show() {
		$this->load->model('User_emergency_model');
		$this->load->model('Upload_pic_model');
		$story_id = intval($this->uri->segment(3));
		$story = $this->Emergency_model->find_by_id($story_id);
		$this->data['story'] = $story;
		$user_id = $this->authorize->current_user();
		if(empty($story['status'])) {
			if (!empty($user_id)) {
				$this->load->model("Invite_model");
				if (!($story['created_by'] == $user_id || $this->Invite_model->is_invited($story_id, "story", $user_id))){
					la_redirect('story/', "事项不存在");
				}
			} else {
				la_redirect('story/', "事项不存在");
			}
		}
		$this->page_title($this->data['story']['title'] . "-行动网");
		$leave_time = (strtotime($this->data['story']['created']) + $this->data['story']['time_cost']*3600*24 - time())/(3600*24);
		$this->data['story']['leave_time'] =  floor(abs($leave_time)) . "天" . floor((abs($leave_time)-(int)abs($leave_time))*24) . "小时";
		if ($leave_time < 0) {
			$this->data['story']['expire'] = 1;
		} else {
			$this->data['story']['expire'] = 0;
		}
		$this->data['pics'] = $this->Upload_pic_model->find_pics($story_id, 'story');
		$this->data['appliers'] = $this->User_emergency_model->find_applier($story_id);
		$this->data['employers'] = $this->User_emergency_model->find_employer($story_id);
		if ($user_id) {
			$this->data['is_applied'] = $this->User_emergency_model->is_applied($story_id, $user_id);
		} else {
			$this->data['is_applied'] = 0;
		}
		$this->load->view('story/show', $this->data);
	}
	/**
	 * 事项报名
	 */
	public function apply() {
		$story_id = intval($this->uri->segment(3));
		$this->load->model('User_emergency_model');
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('story/apply/' . $story_id)), "请先登录");
			die(0);
		}
		$data['user_id'] = $this->authorize->current_user();
		$data['emergency_id'] = $story_id;
		$story = $this->Emergency_model->find_by_id($story_id);
		if ($story['created_by'] != $data['user_id']) {
			if ($this->User_emergency_model->is_applied($story_id, $data['user_id']) > 0) {
				la_redirect('story/show/' . $story_id, "你已经申请过该事务");
			} else {
				$data['created'] = date("Y-m-d H:i:s");
				$this->User_emergency_model->add($data);
				la_redirect('story/show/' . $story_id, "申请成功");
			}
		} else {
			la_redirect('story/show/' . $story_id, "事务创建者不能申请");
		}
		
	}
	
	public function favourite() {
		$story_id = intval($this->uri->segment(3));
		$this->load->model('Favourite_model');
		if (!$this->authorize->is_logged_in()) {
			echo '0';
			//la_redirect('user/login?ref=' . urlencode(site_url('story/favourite/' . $story_id)), "请先登录");
			die(0);
		}
		$data['user_id'] = $this->authorize->current_user();
		$data['target_id'] = $story_id;
		if ($this->Favourite_model->is_favourited($data['user_id'],$story_id, 'story') > 0) {
			echo "2";
			//la_redirect('story/show/' . $story_id, "你已经收藏过该事务");
		} else {
			$data['target_type'] = 'story';
			$data['created'] = date("Y-m-d H:i:s");
			$this->Favourite_model->add($data);
			echo "1";
			//la_redirect('story/show/' . $story_id, "收藏成功");
		}
		
	}
	/**
	 * 删除事项
	 */
	public function delete() {
		$story_id = intval($this->uri->segment(3));
		$story = $this->Emergency_model->find_by_id($expert_id);
		if (!empty($story['created_by']) && $story['created_by'] == $this->authorize->current_user()) {
			$this->Emergency_model->delete($story_id);
			la_redirect("user/story", "行家删除成功");
		} else {
			la_redirect("", "你没有权利进行此操作");
		}
	}
	/**
	 * 挑选某个人为候选
	 */
	public function employ() {
		$story_id = $this->input->get("story_id");
		$applier = $this->input->get("applier");
		$story = $this->Emergency_model->find_by_id($story_id);
		$current_user_id = $this->authorize->current_user();
		if (empty($current_user_id) or $current_user_id != $story['created_by']) {
			la_redirect("/story/show/" . $story_id, "你无权进行此操作");
		}
		$this->load->model("User_emergency_model");
		if (!empty($applier)) {
			foreach($applier as $row) {
				$this->User_emergency_model->update_status($row, $story_id);
			}
		}
		la_redirect("/story/show/" . $story_id, "操作成功");
	}
	/**
	 * 置顶
	 */
	public function top() {
		$this->load->model(array('User_emergency_model', 'User_card_model', 'Log_model'));
		$story_id = intval($this->uri->segment(3));
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('story/top/' . $story_id)), "请先登录");
			die(0);
		}
		$current_user = $this->authorize->current_user();
		$this->data['card_count'] = $this->User_card_model->get_cards_count($current_user);
		if ($_SERVER['REQUEST_METHOD']  == 'POST') {
			$story_id = $this->input->post("story_id");
			$days = $this->input->post("days");
			if ($days > $this->data['card_count']) {
				$this->data['story_id'] = $story_id;
				$this->data['error_message'] = '你的行动卡不足,请购买';
				$this->load->view('story/top', $this->data);
			} else {
				$this->Emergency_model->top($story_id, $days);
				$cards = $this->User_card_model->find_cards($current_user, 0, $days);
				foreach($cards as $card) {
					$this->User_card_model->set_as_used($current_user, $card['card_id']);
				}
				$log = array('type' => 'top', 'created_by' => $current_user, 'created' => date("Y-m-d H:i:s")
									,'params' => json_encode(array('story_id' => $story_id, 'days' => $days)));
				$this->Log_model->add($log);
				$this->data['story_id'] = $story_id;
				$this->load->view('story/top_success', $this->data);
			}
		} else {
			$this->data['story_id'] = $story_id;
			$this->load->view('story/top', $this->data);
		}
	}
	
	function ajax_upload() {
		if (!empty($_FILES)) {
			$tempFile = $_FILES['Filedata']['tmp_name'];
			$targetPath = ROOTPATH . '/img/uploads/';
			$name = date("ymdHis_") . $_FILES['Filedata']['name'];
			$targetFile = $targetPath . $name;
			
			// Validate the file type
			$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
			$fileParts = pathinfo($_FILES['Filedata']['name']);
			$raw_name = str_replace("." . $fileParts['extension'], "", $name);
			if (in_array($fileParts['extension'],$fileTypes)) {
				move_uploaded_file($tempFile,$targetFile);
				$config['image_library'] = 'gd2';
				$config['source_image'] = ROOTPATH . '/img/uploads/' . $name;
				$config['create_thumb'] = TRUE;
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 205;
				$config['height'] = 125;
				
				$this->load->library('image_lib', $config);
				$this->image_lib->resize();
				//echo $raw_name;
				echo '{"result":1,"name":"'. $name . '","rawname":"' . $raw_name. '","ext": ".' . $fileParts['extension']  .'","type": "' . $_FILES['Filedata']['type']  .'"}';
			} else {
				echo '{"result":0}';
			}
		}
		
	}
	
}
